package com.tedu.day08springmvc.controller;

import com.tedu.day08springmvc.mapper.UserMapper;
import com.tedu.day08springmvc.pojo.dto.UserDto;
import com.tedu.day08springmvc.pojo.entity.User;
import com.tedu.day08springmvc.pojo.vo.UserVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

//@Controller
@RestController
public class UserController {
    @Autowired
    private UserMapper userMapper;


    //    @RequestMapping(value = "/user/reg",method = RequestMethod.POST)
    @PostMapping("/user/reg")
//    @ResponseBody
    public String reg(UserDto userDto) {
        User user = new User();
        System.out.println(user);
        BeanUtils.copyProperties(userDto, user);//将UserDto中的数据拷贝到user中
        user.setCreated(new Date());
        System.out.println(user);
        userMapper.insertUser(user);
        return "注册成功";
    }

    //    @RequestMapping(value = "/user/delete",method = RequestMethod.DELETE)
    @DeleteMapping("/user/delete/{id}")
//    @ResponseBody
    public String delete(@PathVariable int id) {
        return userMapper.deleteUser(id) > 0 ? "删除成功" : "删除失败";
    }

    //    @RequestMapping(value = "/user/update",method = RequestMethod.PUT)
    @PutMapping("/user/update")
//    @ResponseBody
    public String update(UserDto userDto) {
        User user = new User();
        BeanUtils.copyProperties(userDto, user);
        return userMapper.updateUser(user) > 0 ? "修改成功" : "修改失败";
    }

    //    @RequestMapping(value = "/user/find" ,method = RequestMethod.GET)
    @GetMapping("/user/find")
//    @ResponseBody
    public List<UserVO> find() {
        List<UserVO> users = userMapper.selectUser();
        return users;
    }

    //
    @GetMapping("/user/findById/{id}")
    public UserVO findById(@PathVariable Integer id) {
        UserVO userVO = userMapper.selectUserById(id);
        return userVO;
    }
}
